
<template>
  <div class="exceptions-container">
    <div class="page-header">
      <div class="header-title">
        <h2>异常处理</h2>
        <span class="subtitle">实时监控和处理运输异常</span>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button type="warning" @click="createException">
            <el-icon><Warning /></el-icon>报告异常
          </el-button>
          <el-button @click="refreshExceptions">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </el-button-group>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：异常列表 -->
      <el-col :span="16">
        <el-card class="exceptions-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span>异常事件</span>
                <el-tag type="danger" class="ml-2">{{ pendingCount }} 个待处理</el-tag>
              </div>
              <div class="header-right">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索异常事件"
                  prefix-icon="Search"
                  clearable
                  class="search-input"
                />
                <el-select v-model="filterStatus" placeholder="状态" clearable>
                  <el-option label="待处理" value="pending" />
                  <el-option label="处理中" value="processing" />
                  <el-option label="已解决" value="resolved" />
                </el-select>
              </div>
            </div>
          </template>

          <el-table
            :data="filteredExceptions"
            style="width: 100%"
            @row-click="handleExceptionClick"
          >
            <el-table-column type="expand">
              <template #default="props">
                <div class="exception-detail">
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="异常描述">{{ props.row.description }}</el-descriptions-item>
                    <el-descriptions-item label="影响范围">{{ props.row.impact }}</el-descriptions-item>
                    <el-descriptions-item label="处理进度">
                      <el-progress 
                        :percentage="props.row.progress"
                        :status="getProgressStatus(props.row.progress)"
                      />
                    </el-descriptions-item>
                    <el-descriptions-item label="处理人">{{ props.row.handler }}</el-descriptions-item>
                  </el-descriptions>
                  
                  <div class="timeline-wrapper">
                    <h4>处理记录</h4>
                    <el-timeline>
                      <el-timeline-item
                        v-for="record in props.row.records"
                        :key="record.time"
                        :timestamp="record.time"
                        :type="record.type"
                      >
                        {{ record.content }}
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="id" label="编号" width="100" />
            <el-table-column prop="type" label="类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getExceptionTypeTag(row.type)">
                  {{ getExceptionTypeText(row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="vehicle" label="车辆" width="120" />
            <el-table-column prop="location" label="位置" show-overflow-tooltip />
            <el-table-column prop="time" label="发生时间" width="160" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button 
                    type="primary" 
                    link
                    :disabled="row.status === 'resolved'"
                    @click.stop="handleException(row)"
                  >
                    处理
                  </el-button>
                  <el-button 
                    type="success" 
                    link
                    :disabled="row.status === 'resolved'"
                    @click.stop="resolveException(row)"
                  >
                    解决
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧：统计分析 -->
      <el-col :span="8">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>异常统计</span>
              <el-radio-group v-model="statsTimeRange" size="small">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <div class="stats-content">
            <div class="stats-overview">
              <div class="stats-item">
                <div class="stats-value">{{ stats.total }}</div>
                <div class="stats-label">总异常数</div>
              </div>
              <div class="stats-item warning">
                <div class="stats-value">{{ stats.pending }}</div>
                <div class="stats-label">待处理</div>
              </div>
              <div class="stats-item success">
                <div class="stats-value">{{ stats.resolved }}</div>
                <div class="stats-label">已解决</div>
              </div>
            </div>

            <el-divider />

            <h4>异常类型分布</h4>
            <div class="chart-placeholder">
              <!-- 这里集成实际的图表组件 -->
              <el-empty description="图表加载中...">
                <template #image>
                  <el-icon style="font-size: 40px"><PieChart /></el-icon>
                </template>
              </el-empty>
            </div>

            <el-divider />

            <h4>平均处理时间</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="车辆故障">2.5小时</el-descriptions-item>
              <el-descriptions-item label="路线偏离">1.2小时</el-descriptions-item>
              <el-descriptions-item label="延迟配送">1.8小时</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>

        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快速处理</span>
            </div>
          </template>

          <div class="quick-actions">
            <el-button type="warning" @click="handleVehicleFailure">
              <el-icon><Van /></el-icon>车辆故障
            </el-button>
            <el-button type="danger" @click="handleRouteDeviation">
              <el-icon><LocationInformation /></el-icon>路线偏离
            </el-button>
            <el-button type="info" @click="handleDeliveryDelay">
              <el-icon><Timer /></el-icon>延迟配送
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 异常处理对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="异常处理"
      width="600px"
    >
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        label-position="top"
      >
        <el-form-item label="处理方案">
          <el-input
            v-model="handleForm.solution"
            type="textarea"
            rows="3"
            placeholder="请输入处理方案"
          />
        </el-form-item>

        <el-form-item label="预计完成时间">
          <el-date-picker
            v-model="handleForm.estimatedTime"
            type="datetime"
            placeholder="选择预计完成时间"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="处理人">
          <el-select
            v-model="handleForm.handler"
            placeholder="选择处理人"
            class="w-full"
          >
            <el-option label="张三" value="张三" />
            <el-option label="李四" value="李四" />
            <el-option label="王五" value="王五" />
          </el-select>
        </el-form-item>

        <el-form-item label="通知相关人员">
          <el-select
            v-model="handleForm.notifyList"
            multiple
            placeholder="选择需要通知的人员"
            class="w-full"
          >
            <el-option label="调度主管" value="dispatcher" />
            <el-option label="车队负责人" value="fleet_manager" />
            <el-option label="客户服务" value="customer_service" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Warning,
  Refresh,
  Search,
  PieChart,
  Van,
  LocationInformation,
  Timer
} from '@element-plus/icons-vue'

// 异常列表数据
const exceptions = ref([
  {
    id: 'EX001',
    type: 'vehicle_failure',
    vehicle: '沪A12345',
    location: '上海市浦东新区张江高科技园区',
    time: '2025-03-14 14:30:00',
    status: 'pending',
    description: '车辆发动机故障，需要维修',
    impact: '影响2个配送订单',
    progress: 0,
    handler: '-',
    records: []
  },
  {
    id: 'EX002',
    type: 'route_deviation',
    vehicle: '沪B67890',
    location: '上海市嘉定区安亭镇',
    time: '2025-03-14 13:45:00',
    status: 'processing',
    description: '车辆偏离预定路线超过5公里',
    impact: '可能导致配送延迟',
    progress: 50,
    handler: '张三',
    records: [
      {
        time: '2025-03-14 13:50:00',
        type: 'warning',
        content: '系统检测到路线偏离'
      },
      {
        time: '2025-03-14 14:00:00',
        type: 'primary',
        content: '已联系司机，正在返回原定路线'
      }
    ]
  }
])

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')

// 筛选后的异常列表
const filteredExceptions = computed(() => {
  let result = exceptions.value

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.id.toLowerCase().includes(keyword) ||
      item.vehicle.toLowerCase().includes(keyword) ||
      item.location.toLowerCase().includes(keyword)
    )
  }

  if (filterStatus.value) {
    result = result.filter(item => item.status === filterStatus.value)
  }

  return result
})

// 待处理异常数量
const pendingCount = computed(() => 
  exceptions.value.filter(item => item.status === 'pending').length
)

// 统计数据
const statsTimeRange = ref('day')
const stats = ref({
  total: 15,
  pending: 5,
  resolved: 8
})

// 异常处理对话框
const handleDialogVisible = ref(false)
const handleFormRef = ref(null)
const handleForm = ref({
  solution: '',
  estimatedTime: '',
  handler: '',
  notifyList: []
})
const currentException = ref(null)

// 获取异常类型标签
const getExceptionTypeTag = (type) => {
  const typeMap = {
    'vehicle_failure': 'danger',
    'route_deviation': 'warning',
    'delivery_delay': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取异常类型文本
const getExceptionTypeText = (type) => {
  const textMap = {
    'vehicle_failure': '车辆故障',
    'route_deviation': '路线偏离',
    'delivery_delay': '延迟配送'
  }
  return textMap[type] || '其他'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'danger',
    'processing': 'warning',
    'resolved': 'success'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决'
  }
  return textMap[status] || '未知'
}

// 获取进度状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return 'exception'
}

// 刷新异常列表
const refreshExceptions = () => {
  ElMessage.success('异常列表已更新')
}

// 创建异常
const createException = () => {
  ElMessage.info('打开异常报告表单')
}

// 处理异常点击
const handleExceptionClick = (row) => {
  console.log('查看异常详情:', row)
}

// 处理异常
const handleException = (exception) => {
  currentException.value = exception
  handleDialogVisible.value = true
}

// 提交处理
const submitHandle = () => {
  if (!currentException.value) return

  // 模拟处理提交
  setTimeout(() => {
    currentException.value.status = 'processing'
    currentException.value.handler = handleForm.value.handler
    currentException.value.progress = 30
    currentException.value.records.push({
      time: new Date().toLocaleString(),
      type: 'primary',
      content: `${handleForm.value.handler}开始处理：${handleForm.value.solution}`
    })

    handleDialogVisible.value = false
    ElMessage.success('处理方案已提交')
  }, 1000)
}

// 解决异常
const resolveException = (exception) => {
  ElMessageBox.confirm(
    '确认该异常已解决？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    exception.status = 'resolved'
    exception.progress = 100
    exception.records.push({
      time: new Date().toLocaleString(),
      type: 'success',
      content: '异常已解决'
    })
    ElMessage.success('异常已标记为已解决')
  }).catch(() => {})
}

// 快速处理功能
const handleVehicleFailure = () => {
  ElMessage.info('打开车辆故障处理向导')
}

const handleRouteDeviation = () => {
  ElMessage.info('打开路线偏离处理向导')
}

const handleDeliveryDelay = () => {
  ElMessage.info('打开延迟配送处理向导')
}
</script>

<style scoped>
.exceptions-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.exceptions-card,
.stats-card,
.quick-actions-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-input {
  width: 200px;
}

.exception-detail {
  padding: 20px;
}

.timeline-wrapper {
  margin-top: 20px;
}

.timeline-wrapper h4 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
}

.stats-content {
  padding: 16px 0;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stats-item {
  text-align: center;
  padding: 16px;
  border-radius: 4px;
  background-color: var(--el-bg-color-page);
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.stats-label {
  margin-top: 8px;
  color: var(--el-text-color-secondary);
}

.stats-item.warning .stats-value {
  color: var(--el-color-warning);
}

.stats-item.success .stats-value {
  color: var(--el-color-success);
}

.chart-placeholder {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 12px;
}

.ml-2 {
  margin-left: 8px;
}

.w-full {
  width: 100%;
}

:deep(.el-table__expanded-cell) {
  padding: 20px !important;
}
</style>